java - 如何为 ImageView 创建一个 id
问题描述
我正在尝试创建一个提醒应用程序。如果用户按下按钮,他可以添加提醒,但我似乎无法让他删除它。事实上,我创建了一个名为添加提醒的方法,当我们选择一天并在 Text 中写入文本时,它会创建一个新的 ImageView。但我无法删除 ImageView,因为我不知道如何找到它。
我已经考虑过放置一个one
等于 ImageView 的变量,然后如果我们重新创建一个回调以将其命名two
为if (one! = Null) {ImageView two = add a callback}
. 但是如果我这样做,我必须手动编写每个变量,因此如果有 20,000 个提醒,则用字母写每个数字 2000 次有点复杂。可以告诉我如何找到我创建的每个 ImageView 以便删除它吗?
顺便说一句,您可以告诉我如何使用 java 代码更改图像的大小。我已经尝试过setMinimumHeight
,setMaxHeight
但它不起作用。
package com.solal.roundbutton;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.LinearLayoutCompat;
import android.annotation.SuppressLint;
import android.content.res.Resources;
import android.media.Image;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import org.w3c.dom.Text;
public class MainActivity extends AppCompatActivity {
public ImageView nouvelleimage( int resources){
ImageView imageView = new ImageView(this);
LinearLayout ll = (LinearLayout)findViewById(R.id.linear);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
imageView.setImageResource(resources);
imageView.setMinimumHeight(100);
imageView.setMaxHeight(300);
ll.addView(imageView, lp);
return imageView;
}
Button button, supprimer;
int numero;
String dd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
supprimer = findViewById(R.id.supprimer);
numero = 0;
dd = String.valueOf(numero);
TextView string = new TextView(this);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ImageView un = nouvelleimage( R.drawable.youstlogo);
}
});
ImageView image1 = nouvelleimage(R.drawable.youstlogo);
nouvelleimage( R.drawable.youstlogo);
supprimer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
public void supprimerimage( ImageView imageView){
LinearLayout ll = (LinearLayout)findViewById(R.id.linear);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
ll.removeView(imageView);
}
}
解决方案
您可以在班级中创建一个列表:
public class MainActivity extends AppCompatActivity {
List<ImageView> images = new ArrayList<>();
...
然后在按钮点击监听器:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ImageView image = nouvelleimage( R.drawable.youstlogo);
images.add(image):
}
});
现在,如果要删除第 n 个图像,可以调用:
ImageView image = images.remove(n - 1):
deleteImage(image):