setVisibility(View.INVISIBLE)导致异常,为什么?

时间:2017-03-08 18:02:19

标签: android eclipse

为什么我的setVisibility(View.INVISIBLE)会导致异常         TextView的setVisibility有效。我也试过为ImageView设置它也不起作用 - 我也得到了异常

public void alertdiag() {
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
    LayoutInflater inflater = this.getLayoutInflater();
    View dialogView = inflater.inflate(R.layout.alertdiag_layout, null);
    dialogBuilder.setView(dialogView).show();

    View Divider1 = (View) dialogView.findViewById(R.style.Divider1);
    Divider1.setVisibility(View.INVISIBLE); //causes java.lang.IllegalStateException: Could not execute method of the activity"

    TextView HELP0 = (TextView) dialogView.findViewById(R.id.HELP0); 
    HELP0.setVisibility(View.INVISIBLE); // this works
}

alertdiag_layout.xml:

<View style="@style/Divider1"
    android:layout_below="@+id/HELP3"
    android:background="#000000"            
    android:layout_alignRight="@+id/HELP_FIX_LINE"
    android:layout_alignLeft="@+id/HELP3"
/>  

<TextView
    android:id="@+id/HELP0"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_below="@+id/HELP_FIX_LINE"     
    android:textStyle="bold"
    android:typeface="normal"
/>          

styles.xml:

<style name="Divider1">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">1dp</item>
</style>

2 个答案:

答案 0 :(得分:1)

您正尝试将可见性设置为a 风格(R.style.Divider1)

在您的视图中添加ID并将R.style.Divider1更改为R.id.yourNewId

  <View style="@style/Divider1" android:id="@+id/yourNewId"
    android:layout_below="@id/HELP3" android:background="#000000"
    android:layout_alignRight="@id/HELP_FIX_LINE"         
    android:layout_alignLeft="@id/HELP3" />

答案 1 :(得分:0)

为您的视图添加ID属性

  <View style="@style/Divider1"
   android:id="@+id/my_view"
   android:layout_below="@id/HELP3"
   android:background="#000000"         
   android:layout_alignRight="@id/HELP_FIX_LINE"
   android:layout_alignLeft="@id/HELP3"
    /> 

注意:我分别用@ id / HELP3和@ id / HELP_FIX_LINE切换了@ + id / HELP3和@ + id / HELP_FIX_LINE,因为仅在给视图提供id时才使用@ + id /。它不用于引用其他视图。

现在,更改此行代码

 View Divider1 = (View) dialogView.findViewById(R.style.Divider1);

View Divider1 = (View) dialogView.findViewById(R.id.my_view);

它将找到具有给定id的视图,而不是样式。

要使视图不可见,您需要设置

Divider1.setVisibility(View.INVISIBLE);

必须在视图上使用setVisibility,而不是在样式上使用。