2016-04-23 8 views
-1

ImageButtonからレイアウトを変更しようとしましたが、私の電話でそれを実行したときに、プログラムが停止したと言われています。レイアウトの変更エラー?

Java;

public class MainActivity extends AppCompatActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     ImageButton ImageButton = (ImageButton) findViewById(R.id.image); 
     ImageButton.setBackgroundColor(1); 

     ImageButton.setOnClickListener(new View.OnClickListener(){ 

      @Override 
      public void onClick(View view) 
      { 
       setContentView(R.id.aaa); 
      } 
     }); 


    } 
} 

最初のレイアウトのためのXML:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context="com.example.bassammetwally.anew.MainActivity"> 
    <RelativeLayout 
     android:layout_width="420dp" 
     android:layout_height="50dp" 
     android:background="#3955a1"> 
     <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Writer's Block" 
      android:textColor="#ffffff" 
      android:textSize="30dp" 
      android:layout_marginLeft="10dp" 
      android:layout_marginTop="4dp" 
      android:id="@+id/Asd"/> 
     <ImageButton 
      android:layout_width="20dp" 
      android:layout_height="40dp" 
      android:src="@drawable/pen" 
      android:layout_marginLeft="380dp" 
      android:layout_marginTop="5dp" 
      android:scaleType="fitXY" 
      android:adjustViewBounds="true" 
      android:id="@+id/image"/> 
     </RelativeLayout> 
</LinearLayout> 

に変更するための第2のレイアウト。

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:id="@+id/aaa"> 
    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Ans"/> 

</LinearLayout> 

私の文法とは関係があると思います。

+0

を確認したい場合。これは、2番目のレイアウトの 'LinearLayout'のIDです。レイアウト識別子は、最初の 'setContentView()'呼び出しで持っているものと同様に 'R.layout'で始まります。また、そのようなレイアウトを切り替えることは、通常、良い考えではありません。 –

+0

これを確認してくださいhttp://stackoverflow.com/questions/2335813/how-to-inflate-one-view-with-a-layout?rq=1 –

答えて

0

あなたは代わりにID view.xmlが希望のレイアウトである

setContentView(R.layout.view); 

のレイアウトの参照を使用する必要があります。

あなたのアプローチを再考することもできます。 ImageButtonはもはや使用できなくなり、表示される新しいビューに対してはfindViewByIdを呼び出す必要があるため、フラグメントを使用するとレイアウトを完全に置き換えるよりも優先されます。

あなただけのレイアウトファイルをロードして、現在のレイアウトに追加し、 `R.id.aaa`レイアウトではありませんInflating one layout

関連する問題