片段中的按钮不起作用

时间:2015-12-01 07:52:42

标签: android button fragment

如果我从共享首选项中删除所有内容,我可以让我的按钮工作。如何让我的按钮工作并保持我的偏好?

我不确定我是否正确发布了我的代码。我很少发布任何内容。如果我做错了,请让我知道我需要做些什么来解决它。

public class FairgroveDirectory extends Fragment
{
    ImageButton fairgrove_cell;

    public FairgroveDirectory() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fairgrove_directory, container, false);
        fairgrove_cell = (ImageButton) root.findViewById(R.id.fairgrove_cell);
        fairgrove_cell.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                Toast.makeText(getActivity(), "You Clicked the button!", Toast.LENGTH_LONG).show();
            }
        });
        SharedPreferences fontSize =PreferenceManager.getDefaultSharedPreferences(getActivity());

        // Get the font size option.  We use "FONT_SIZE" as the key.
        // Make sure to use this key when you set the value in SharedPreferences.
        // We specify "Medium" as the default value, if it does not exist.
        String fontSizePref = fontSize.getString("FONT_SIZE", "Small");

        // Select the proper theme ID.
        // These will correspond to your theme names as defined in themes.xml.
        Context contextThemeWrapper = new ContextThemeWrapper(getActivity(), R.style.FontSizeSmall);
        if ("Medium".equals(fontSizePref)) {
            contextThemeWrapper = new ContextThemeWrapper(getActivity(), R.style.FontSizeMedium);
        }
        else if ("Large".equals(fontSizePref)) {
            contextThemeWrapper = new ContextThemeWrapper(getActivity(), R.style.FontSizeLarge);
        }
        else if ("XLarge".equals(fontSizePref)) {
            contextThemeWrapper = new ContextThemeWrapper(getActivity(), R.style.FontSizeXLarge);
        }
        // Set the theme for the activity.

        // clone the inflater using the ContextThemeWrapper
        LayoutInflater localInflater = inflater.cloneInContext(contextThemeWrapper);

        // inflate the layout using the cloned inflater, not default inflater
        return localInflater.inflate(R.layout.fairgrove_directory, container, false);
    }
}

3 个答案:

答案 0 :(得分:0)

问题是由:

引起的
return localInflater.inflate(R.layout.fairgrove_directory, container, false);

行,因为访问来自fairgrove_directory的不同对象的视图并从onCreateView返回新的View对象。

使用相同的对象root从中访问像ImageVIew这样的视图作为来自onCreateView的视图返回:

return root;

答案 1 :(得分:0)

替换return localInflater.inflate(R.layout.fairgrove_directory, container, false);  与return root;

答案 2 :(得分:0)

替换" LayoutInflater localInflater = inflater.cloneInContext(contextThemeWrapper);         //使用克隆的inflater扩展布局,而不是默认的inflater         return localInflater.inflate(R.layout.fairgrove_directory,container,false);"
 返回" root&#34 ;;