2013-02-15 22 views
0

我是新來的Android,並希望從片段傳遞一些文本到自定義視圖。在自定義視圖中,我想使用canvas.drawText來定位字符串。我想使用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; 
    } 
} 

我爲視圖1(我的自定義視圖)一個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。

回答

1

您可以動態創建com.example.stuff.View1自定義視圖,即不要將其添加到xml中,而是使用代碼添加它。然後您可以通過com.example.stuff.View1constructor中的文字。
其他方法可以在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); 
+0

你能提供更多的細節嗎?也許是示例代碼?我上面編輯了我的問題。我想知道如何通過View1的構造函數提供文本?謝謝。 – lynvie 2013-02-16 03:28:06

相關問題