2015-06-08 76 views
3

我开始在我的项目中使用RoboGuice。我可以轻松地在片段和活动中注入视图,但是我对cusom视图有一些麻烦。 我每次都得到空ptr异常。无法使用RoboGuice将视图注入到自定义类中

根据RoboGuice's example和我一样的我的自定义类:

测试活动

@ContentView(R.layout.test_layout) 
public class TestActivity extends RoboActivity { 

    @InjectView(R.id.testView_1) TestView testView; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
    } 
} 

TestView

public class TestView extends LinearLayout { 


    @InjectView(R.id.log_in_tab) View logInTab; 

    public TestView(Context context) { 
     super(context); 
     initView(); 
    } 

    public TestView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     initView(); 
    } 

    public TestView(Context context, AttributeSet attrs, int defStyleAttr) { 
     super(context, attrs, defStyleAttr); 
     initView(); 
    } 


    @Override 
    public void onFinishInflate() { 
     super.onFinishInflate(); 

     if (logInTab == null) 
      Toast.makeText(getContext(), "Still NULL", Toast.LENGTH_LONG).show(); 
     else 
      Toast.makeText(getContext(), "Ok", Toast.LENGTH_LONG).show(); 

    } 

    public void initView() { 

     inflate(getContext(), R.layout.login_view, this); 
     RoboGuice.injectMembers(getContext(), this); 
    } 


} 

登录视图的XML是pastebin here.

测试布局

<?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"> 

    <view 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     class="hu.illion.kwindoo.view.test.TestView" 
     android:id="@+id/testView_1"/> 
</LinearLayout> 

吐司总是说logInTab为空。

如果可以,请帮助。

+0

看不到'R.您的布局中的id.log_in_tab'。 –

+0

@JiangYD这是在pastebin,但不知何故链接被打破,所以我编辑帖子。 –

+0

@JiangYD无法编辑帖子,编辑按钮无效,不知道为什么。 –

回答

5

我不知道为什么没有代码示例,但是当我必须注入自定义视图我使用injectViewMembers。

希望这对你的工作:

public void initView() { 
    inflate(getContext(), R.layout.login_view, this); 
    RoboGuice.injectMembers(getContext(), this); 
    RoboGuice.getInjector(getContext()).injectViewMembers(this); 
} 
+0

嗯,我还没有看到这样的任何代码示例,但这个definetly作品。谢谢,现在是时候减少代码基地了:) –

1

除了以前的答案,你应该使用下面的方法来真正开始利用喷射的观点:

@Override 
protected void onFinishInflate() { 
    super.onFinishInflate(); 

    someTextView.setText("Some text"); 
} 
相关问题