0

私は Android を初めて使用し、フラグメントからカスタム ビューにテキストを渡したいと考えています。canvas.drawText文字列を配置するために使用したいカスタムビュー内。使用したい理由canvas.drawTextは、一部のグラフィックスの位置との一貫性のためです。

これにはどのような手順がありますか?

明確にするために、私のフラグメントには次のようなものがあります。

public class Fragment1 extends Fragment {

private TextView view;
private TextView txtBox;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_layout, container,false);
    txtBox = (TextView) view.findViewById(R.id.TxtBox);
            String myString = "testing";
            txtBox.setText(myString);
    return view;
    }
}

View1 (カスタム ビュー) 用の fragment_layout.xml ファイルがあります。

<com.example.stuff.View1
    android:id="@+id/TxtBox"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

カスタムビュー内で行いたい呼び出し:

public class View1 extends TextView {

    //constructors:
    public View1(Context context, AttributeSet ats, int ds) {
        super(context, ats, ds);
        init();
    }

    public View1(Context context) {
        super(context);
        init();
    }

    public View1(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }
...
canvas.drawText(myString, margin1, margin2, paint);
....
}

...そして私が望むのはmyString、Fragment1.java から View1.java に移動することです。

4

2 に答える 2

1

カスタム ビューを動的に作成できますcom.example.stuff.View1。つまり、xml に追加するのではなく、コードを使用して追加します。そして、テキストを の に渡すことができconstructorますcom.example.stuff.View1
他の方法は、com.example.stuff.View1クラスでメソッドを作成し、そこにテキストを設定することです。例えば

public class View1 extends TextView {

    //constructors:
    public View1(Context context, AttributeSet ats, int ds) {
        super(context, ats, ds);
        init();
    }

    public View1(Context context) {
        super(context);
        init();
    }

    public View1(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public void setMyText(String string) {
        myString=string;
    }
...
canvas.drawText(myString, margin1, margin2, paint);
....
}

次に、コードで次のようなことを行います

View view = inflater.inflate(R.layout.fragment_layout, container,false);
    txtBox = (TextView) view.findViewById(R.id.TxtBox);
    String myString = "testing";
    txtBox.setMyText(myString);
于 2013-02-15T08:17:02.713 に答える