私はこのカスタムビューを持っています:
package com.myapp;
public class CustomView extends View {
public CustomView(Context c) {
super(c);
CharSequence text = "HELLO";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(c, text, duration);
toast.show();
}
}
私はxmlで配置したかったので、これは私が書いたものですmain.xml
:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tableLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<view
class="com.myapp.CustomView"
id="@+id/customText"
android:layout_width="match_parent"
android:layout_height="30dp"
android:background="@color/red"
/>
</LinearLayout>
の内容strings.xml
:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="red">#FF0000</color>
</resources>
とにかく、アプリケーションを開いたときに赤いビューが表示されず、トーストも表示されません。何が欠けていますか?
アップデート:
私はそれを言及するのを忘れていました、私もこの方法を試しました:
<com.myapp.CustomView
id="@+id/inputText"
android:layout_width="match_parent"
android:layout_height="30dp"
android:background="@color/red"
/>
しかし、それは機能しません
アップデート
これは完全なコードです:
MyActivity.java
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
CustomView.java:
public class CustomView extends View {
@Override
public CustomView(Context context) {
super(context);
Log.d("myapp.contextview","context constructor");
throw new RuntimeException("Trying to crash the app");
}
@Override
public CustomView(Context context, AttributeSet attrs) {
super(context,attrs);
Log.d("myapp.contextview","context+attributeset constructor");
throw new RuntimeException("Trying to crash the app");
}
@Override
public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context,attrs,defStyleAttr);
Log.d("myapp.contextview","context+attributeset+defstyleattr constructor");
throw new RuntimeException("Trying to crash the app");
}
}
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tableLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.myapp.CustomView
id="@+id/customText"
android:layout_width="match_parent"
android:layout_height="30dp"
android:background="@color/red"
/>
</LinearLayout>
文字列.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="red">#FF0000</color>
</resources>