[英]How to make one imageview disappear when another imageview is pressed?
[英]How to make one ImageView invisible when another clickable ImageView is pressed?
我試圖使ImageView(bul1)在按ImageView(Seethrough)時消失。 當我嘗試運行此代碼時,出現空指針錯誤。 怎么了
JAVA代碼
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView seethrough1 = (ImageView) findViewById(R.id.Seethrough);
final ImageView view1 = (ImageView) findViewById(R.id.bul1);
seethrough1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(view1.getVisibility() == View.VISIBLE)
{
view1.setVisibility(View.INVISIBLE);
}
}
});
}
XML代碼
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="match_parent"
android:layout_height="300dp"
android:paddingBottom="6dp"
android:src="@drawable/gun"
android:clickable="true"
android:id="@+id/Seethrough"
android:onClick="next"
/>
<ImageView
android:layout_width="30dp"
android:layout_height="wrap_content"
android:src="@drawable/bullet"
android:id="@+id/bul1"
/>
</LinearLayout>
您需要將透明點的onClickListener及其onClick XML屬性進行協調。 我建議從xml中刪除此行:
android:onClick="next"
並將代碼放在下一個方法中(如果有的話)
public void next (View v){
some code
}
在可見性后面或之前,檢查是否更適合您:
@Override
public void onClick(View v) {
//place some code here
if(view1.getVisibility() == View.VISIBLE){
view1.setVisibility(View.INVISIBLE);
}
//or here
}
我認為他們是沒有xml代碼的問題,請嘗試按以下方式編寫xml,
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:layout_width="match_parent"
android:layout_height="300dp"
android:paddingBottom="6dp"
android:src="@drawable/gun"
android:clickable="true"
android:id="@+id/Seethrough"
android:onClick="next"
/>
<ImageView
android:layout_width="30dp"
android:layout_height="wrap_content"
android:src="@drawable/bullet"
android:id="@+id/bul1"
/>
</LinearLayout>
如果返回NullPointerExeption,我認為您的ImageView為Null,因為
setContentView(R.layout.activity_main);
並且activity_main.xml與您的帖子內容不同,請檢查布局名稱,然后重試。
我發現我應該在方法內部而不是之前聲明圖像視圖。
像這樣
public void onClick(View v) {
ImageView seethrough1 = (ImageView) findViewById(R.id.Seethrough);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.