Home Php C# Sql C C++ Javascript Python Java Go Android Git Linux Asp.net Django .net Node.js Ios Xcode Cocoa Iphone Mysql Tomcat Mongodb Bash Objective-c Scala Visual-studio Apache Elasticsearch Jar Eclipse Jquery Ruby-on-rails Ruby Rubygems Android-studio Spring Lua Sqlite Emacs Ubuntu Perl Docker Swift Amazon-web-services Svn Html Ajax Xml Java-ee Maven Intellij-idea Rvm Macos Unix Css Ipad Postgresql Css3 Json Windows-server Vue.js Typescript Oracle Hibernate Internet-explorer Github Tensorflow Laravel Symfony Redis Html5 Google-app-engine Nginx Firefox Sqlalchemy Lucene Erlang Flask Vim Solr Webview Facebook Zend-framework Virtualenv Nosql Ide Twitter Safari Flutter Bundle Phonegap Centos Sphinx Actionscript Tornado Register | Login | Edit Tags | New Questions | 繁体 | 简体


10 questions online user: 18

155
votes
answers
13 views
+10

Line Break in XML formatting?

when editing a String in XML I need to add line breaks. And I wanted to ask what is the RIGHT form when programming for android? Because <br> works but ECLIPSE marks the area as problematic. If I check out suggestions Eclipse tells me that I shall add a end tag </br> - IF I add that the line break dissapears...

So the one works but is marked as problematic, the other works not but Eclipse tells me its ok..

What form shall I use?

up vote 132 down vote accepted favorite
沙发
+1320
+50

Use for a line break and if you want to insert a tab.

You can also use some XML tags for basic formatting: <b> for bold text, <i> for italics, and <u> for underlined text.

Other formatting options are shown in this article on the Android Developers' site:
https://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling

+140

If you are refering to res strings, use CDATA with .

<string name="about">
    <![CDATA[
 Author: Sergio Abreu

 http://sites.sitesbr.net
  ]]>        
</string>

最好的答案完美無缺! - Narh-ngwah Ebenezer Watts 5月27日凌晨2點37分

+40

Also you can add <br> instead of .

And then you can add text to TexView:

articleTextView.setText(Html.fromHtml(textForTextView));
+30

Take note: I have seen other posts that say &#xA; will give you a paragraph break, which oddly enough works in the Android xml String.xml file, but will NOT show up in a device when testing (no breaks at all show up). Therefore, the shows up on both.

你能告訴我們什麼是格式嗎?所有字符的表格的網址可能是 - shareef 18年10月17日在13:13

+20

Here is what I use when I don't have access to the source string, e.g. for downloaded HTML:

// replace newlines with <br>
public static String replaceNewlinesWithBreaks(String source) {
    return source != null ? source.replaceAll("(?:
|
)","<br>") : "";
}

For XML you should probably edit that to replace with <br/> instead.

Example of its use in a function (additional calls removed for clarity):

// remove HTML tags but preserve supported HTML text styling (if there is any)
public static CharSequence getStyledTextFromHtml(String source) {
    return android.text.Html.fromHtml(replaceNewlinesWithBreaks(source));
}

...and a further example:

textView.setText(getStyledTextFromHtml(someString));

很好,工作很棒。謝謝 - sandeepmaaram 2014年11月24日11:40

0
votes
answers
31 views
+10

使用Perl獲取XML數據

-1

我必須從xml中獲取「總計」值的值,我已經爲它編寫了perl腳本,但是對於總計xml標記路徑已經發生了一些錯誤。請指導正確的路徑。使用Perl獲取XML數據

以下是XML。

<TotalForServiceSummary> 
    <GrandTotal><![CDATA[1246.00]]></GrandTotal> 
</TotalForServiceSummary> 

腳本:

my $salesOrderNumber =s hift @ARGV; 
my $billRunID = shift @ARGV; 
my $customerNodeID = shift @ARGV; 
my $invoiceID = shift @ARGV; 
my $billRunDate =shift @ARGV; 

my $filename = "So_".$salesOrderNumber."_".$billRunID."_".$customerNodeID."_".$invoiceID."_".$billRunDate; 

my $file = `ls /svw/svwsit2b/data/server/invoices/sap_equip_invoice/$filename*.xml`; 

my $return; 

open(XML, $file) or die "Cannot open $file for reading: $!
"; 

while (my $line = <XML>) { 

    if ($line =~ /<EquipSalesTotalChargeIncTax>/i) { 
     my $xml = new XML::Simple; 
     my $ref3 = $xml->XMLin($line); 
     $return = $return . $ref3; 
    }  
} 
+1

我已經修復了你的代碼的格式(這包括添加缺少的結束'}')。不客氣,但請在將來自己做。如果您要求一羣陌生人閱讀並理解您的代碼,那麼儘可能簡單地爲他們完成該任務只是禮貌。 –

+1

顯而易見的錯誤是,示例輸入與代碼中的內容不匹配 –

+1

*「我...對於總計xml標記路徑發生了一些錯誤」*但是您的代碼不顯示任何「XML標籤路徑」。您需要展示您的真實代碼和數據才能獲得適當的幫助。 – Borodin

沙发
0
4

有相當多的誤解回事。

您不需要一次讀取一行XML文件。你應該讓XMLIn()一次處理所有的XML - 實際上你可以傳遞它一個文件名,它將打開文件並從中讀取所有的XML。

但是,你也應該注意從XML::Simple documentation本節:

STATUS這個模塊

使用本模塊中新代碼是不鼓勵的。其他模塊是 可用,提供更直接和一致的 接口。特別強烈建議XML::LibXMLXML::Twig是一個很好的選擇。

該模塊的主要問題是大量的選項 (其中一些具有不幸的默認值)以及這些選項交互的 中的任意方式 - 通常會產生意想不到的結果。

歡迎使用修補程序和文檔修補程序的修補程序,但不可能添加新的 功能。

您應該認真考慮切換到上述替代庫之一。

而且,這兩條線沒有任何意義:

my $ref3 = $xml->XMLin($line); 
$return = $return . $ref3; 

$ref3將包含一個參考(可能爲哈希)。它的字符串表示看起來像HASH(0x12345678),這不太可能是你想要的。

更新:用XML :: LibXML解決這個問題看起來像這樣。但我懷疑你是在簡化你的問題,所以這個解決方案可能不適合你。

#!/usr/bin/perl 

use strict; 
use warnings; 
use feature 'say'; 

use XML::LibXML; 

# My XML is in "total.xml". 
my $doc = XML::LibXML->new->parse_file('total.xml'); 

say $doc->findvalue('//TotalForServiceSummary/GrandTotal'); 

更新2:你的代碼中的一些其他問題。

你行:

my $salesOrderNumber =shift @ARGV; 
my $billRunID = shift @ARGV; 

等等...

更好地寫爲:

my ($salesOrderNumber, $billRunID, $customerNodeID, 
    $invoiceID, $billRunDate) = @ARGV; 

的??3210函數是一個跨平臺的方式來獲得文件名列表 - 無需使用外部程序像ls

請使用詞法文件句柄和open()的三參數版本。

open my $xml_fh, '<', $file 
    or die "Can't open $file: $!
"; 

調用構造函數(new XML::Simple)的「間接對象」的方式將有可能導致你難以找到在某一點問題。代替使用更好。

+0

由於OP代碼正在查找包含「EquipSalesTotalChargeIncTax」標籤的行,因此不確定您的第一次更新是否完全正確 –

+0

@ChrisTurner:是的,我基於樣本數據而不是代碼。這就是爲什麼我說我認爲他已經過分簡化了這個問題(並且可能在這個過程中讓自己感到困惑)。 –

+0

感謝Chris&Dave提供了所有的建議和幫助,你們的人是對的,我試圖過分簡化它,因爲示例給出的是一個非常大的XML文件的一部分,也有很多'GrandTotal'標籤,但我需要獲取一個在之下。 – Vijay

0
votes
answers
34 views
+10

滾動不能僅在屏幕中間工作

0

我正在開發購物應用程序。在一個活動中,我在表格佈局中有一個項目列表。該表具有標題行和兩個頁腳行。我只想在中間激活滾動。滾動不能僅在屏幕中間工作

爲了實現我有3個TableLayouts。 1只包含標題行。 1包含主項目列表,1包含頁腳行。以下是我的代碼。

<?xml version="1.0" encoding="utf-8"?> 
<GridLayout 
    android:layout_height="fill_parent" 
    android:layout_width="match_parent" 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" 
    tools:context="com.example.ahnaf.homemgt.Cart" 
    android:columnCount="1" 
    android:rowCount="5" 
    > 
    <android.support.design.widget.AppBarLayout 
     android:id="@+id/appBarLayout" 
     android:layout_width="match_parent" 
     android:layout_height="50dp" 
     android:theme="@style/AppTheme.AppBarOverlay" 
     android:background="@android:color/black" 
     app:layout_constraintEnd_toEndOf="parent" 
     app:layout_constraintStart_toStartOf="parent" 
     app:layout_constraintTop_toTopOf="parent"> 


     <Button 
      android:id="@+id/button7" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_gravity="center" 
      android:layout_weight="1" 
      android:background="@android:color/transparent" 
      android:text="HomeMGT" /> 

    </android.support.design.widget.AppBarLayout> 

    <TableLayout 
     android:layout_height="wrap_content" 
     android:layout_width="match_parent" 
     android:stretchColumns="0,1,2,3" 
     > 
     <TableRow 
      android:minHeight="40dp"> 

      <Button 
       android:id="@+id/addItem" 
       style="@style/Widget.AppCompat.Button.Borderless" 
       android:layout_width="wrap_content" 
       android:layout_height="match_parent" 
       android:layout_span="4" 
       android:background="@android:color/holo_blue_dark" 
       android:minHeight="0dp" 
       android:minWidth="0dp" 
       android:onClick="addItem" 
       android:text="Add Item To Cart" 
       android:textAppearance="@style/TextAppearance.AppCompat.Body1" /> 

     </TableRow> 

    </TableLayout> 

    <TableLayout 
     android:layout_height="wrap_content" 
     android:layout_width="match_parent" 
     android:stretchColumns="0,1,2,3" 
     > 
     <TableRow 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:background="@android:color/background_dark" 
      android:gravity="center_horizontal"> 


      <TextView 
       android:id="@+id/textView" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_column="0" 
       android:text="Name" 
       android:textColor="@android:color/background_light" 
       android:textAlignment="center"/> 


      <TextView 
       android:id="@+id/textView2" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_column="1" 
       android:text="Qty" 
       android:textColor="@android:color/background_light" 
       android:textAlignment="center"/> 

      <TextView 
       android:id="@+id/textView3" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_column="1" 
       android:text="Price" 
       android:textColor="@android:color/background_light" 
       android:textAlignment="center"/> 

      <TextView 
       android:id="@+id/textView4" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_column="1" 
       android:text="Subtotal" 
       android:textColor="@android:color/background_light" 
       android:textAlignment="center"/> 


     </TableRow> 

    </TableLayout> 


    <ScrollView> 
     <TableLayout 
      android:layout_height="wrap_content" 
      android:layout_width="match_parent" 
      android:stretchColumns="0,1,2,3" 
      android:id="@+id/myTableLayout"> 

     </TableLayout> 
    </ScrollView> 

    <TableLayout 
     android:layout_height="wrap_content" 
     android:layout_width="match_parent" 
     android:stretchColumns="0,1,2,3" 
     android:layout_gravity="bottom" 
     > 
     <TableRow 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:background="@android:color/background_dark" 
      android:gravity="center_horizontal"> 

      <TextView 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_column="2" 
       android:text="Total" 
       android:textColor="@android:color/background_light" 
       android:textAlignment="center"/> 

      <TextView 
       android:id="@+id/total" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_column="3" 
       android:textColor="@android:color/background_light" 
       android:textAlignment="center"/> 


     </TableRow> 

     <TableRow 
      android:minHeight="40dp"> 

      <Button 
       android:id="@+id/cashOut" 
       style="@style/Widget.AppCompat.Button.Borderless" 
       android:layout_width="wrap_content" 
       android:layout_height="match_parent" 
       android:layout_span="4" 
       android:background="@android:color/holo_blue_dark" 
       android:minHeight="0dp" 
       android:minWidth="0dp" 
       android:onClick="addItem" 
       android:text="Cash Out" 
       android:textAppearance="@style/TextAppearance.AppCompat.Body1" /> 

     </TableRow> 
    </TableLayout> 


</GridLayout> 

起初一切正常,但是當我添加了太多的項目我的滾動不起作用。包含「取出」按鈕和總文本視圖的最後兩行也會消失。我在這裏做錯了什麼?

*****************************用以下代碼解決************ *******

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto"> 

    <GridLayout 
     android:layout_height="fill_parent" 
     android:layout_width="match_parent" 
     android:layout_below="@id/appBarLayout" 
     android:columnCount="1" 
     android:rowCount="5" 
     > 

     <TableLayout 
      android:layout_height="wrap_content" 
      android:layout_width="match_parent" 
      android:stretchColumns="0,1,2,3" 
      > 
      <TableRow 
       android:minHeight="40dp"> 

       <Button 
        android:id="@+id/addItem" 
        style="@style/Widget.AppCompat.Button.Borderless" 
        android:layout_width="wrap_content" 
        android:layout_height="match_parent" 
        android:layout_span="4" 
        android:background="@android:color/holo_blue_dark" 
        android:minHeight="0dp" 
        android:minWidth="0dp" 
        android:onClick="addItem" 
        android:text="Add Item To Cart" 
        android:textAppearance="@style/TextAppearance.AppCompat.Body1" /> 

      </TableRow> 

     </TableLayout> 

     <TableLayout 
      android:layout_height="wrap_content" 
      android:layout_width="match_parent" 
      android:stretchColumns="0,1,2,3" 
      > 
      <TableRow 
       android:layout_width="fill_parent" 
       android:layout_height="wrap_content" 
       android:background="@android:color/background_dark" 
       android:gravity="center_horizontal"> 


       <TextView 
        android:id="@+id/textView" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_column="0" 
        android:text="Name" 
        android:textColor="@android:color/background_light" 
        android:textAlignment="center"/> 


       <TextView 
        android:id="@+id/textView2" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_column="1" 
        android:text="Qty" 
        android:textColor="@android:color/background_light" 
        android:textAlignment="center"/> 

       <TextView 
        android:id="@+id/textView3" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_column="1" 
        android:text="Price" 
        android:textColor="@android:color/background_light" 
        android:textAlignment="center"/> 

       <TextView 
        android:id="@+id/textView4" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_column="1" 
        android:text="Subtotal" 
        android:textColor="@android:color/background_light" 
        android:textAlignment="center"/> 


      </TableRow> 

     </TableLayout> 


     <ScrollView 
      android:layout_height="wrap_content" 
      android:layout_width="match_parent"> 
      <!--<LinearLayout--> 
       <!--android:layout_width="match_parent"--> 
       <!--android:layout_height="wrap_content"--> 
       <!--android:orientation="vertical"--> 
       <!--android:id="@+id/myLinearLayout">--> 
       <TableLayout 
        android:layout_width="match_parent" 
        android:layout_height="match_parent" 
        android:stretchColumns="0,1,2,3" 
        android:id="@+id/myTableLayout"> 

       </TableLayout> 





      <!--</LinearLayout>--> 
     </ScrollView> 
    </GridLayout> 

    <GridLayout 
     android:layout_height="wrap_content" 
     android:layout_width="wrap_content" 
     android:layout_alignParentBottom="true" 
     android:columnCount="1" 
     android:rowCount="5" 
     > 
     <TableLayout 
      android:layout_height="wrap_content" 
      android:layout_width="match_parent" 
      android:stretchColumns="0,1,2,3" 
      android:layout_gravity="bottom" 
      > 
      <TableRow 
       android:layout_width="fill_parent" 
       android:layout_height="wrap_content" 
       android:background="@android:color/background_dark" 
       android:gravity="center_horizontal"> 

       <TextView 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_column="2" 
        android:text="Total" 
        android:textColor="@android:color/background_light" 
        android:textAlignment="center"/> 

       <TextView 
        android:id="@+id/total" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_column="3" 
        android:textColor="@android:color/background_light" 
        android:textAlignment="center"/> 


      </TableRow> 

      <TableRow 
       android:minHeight="40dp"> 

       <Button 
        android:id="@+id/cashOut" 
        style="@style/Widget.AppCompat.Button.Borderless" 
        android:layout_width="wrap_content" 
        android:layout_height="match_parent" 
        android:layout_span="4" 
        android:background="@android:color/holo_blue_dark" 
        android:minHeight="0dp" 
        android:minWidth="0dp" 
        android:onClick="addItem" 
        android:text="Cash Out" 
        android:textAppearance="@style/TextAppearance.AppCompat.Body1" /> 

      </TableRow> 
     </TableLayout> 

    </GridLayout> 

</RelativeLayout> 
沙发
0
0

讓我知道,如果下面的代碼爲你工作,我在一個相對佈局包裹一切再分你的網格佈局分爲兩個,第一個是在,而頂部另一種是固定在屏幕的屏幕,頂級的GridView的底部有你滾動視圖是滾動和「頁腳」是粘性使剛剛中間部分卷軸:

<RelativeLayout android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto"> 

    <GridLayout 
     android:layout_height="fill_parent" 
     android:layout_width="match_parent" 
     android:layout_below="@id/appBarLayout" 
     android:columnCount="1" 
     android:rowCount="5" 
     > 

    <TableLayout 
     android:layout_height="wrap_content" 
     android:layout_width="match_parent" 
     android:stretchColumns="0,1,2,3" 
     > 
     <TableRow 
      android:minHeight="40dp"> 

      <Button 
       android:id="@+id/addItem" 
       style="@style/Widget.AppCompat.Button.Borderless" 
       android:layout_width="wrap_content" 
       android:layout_height="match_parent" 
       android:layout_span="4" 
       android:background="@android:color/holo_blue_dark" 
       android:minHeight="0dp" 
       android:minWidth="0dp" 
       android:onClick="addItem" 
       android:text="Add Item To Cart" 
       android:textAppearance="@style/TextAppearance.AppCompat.Body1" /> 

     </TableRow> 

    </TableLayout> 

    <TableLayout 
     android:layout_height="wrap_content" 
     android:layout_width="match_parent" 
     android:stretchColumns="0,1,2,3" 
     > 
     <TableRow 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:background="@android:color/background_dark" 
      android:gravity="center_horizontal"> 


      <TextView 
       android:id="@+id/textView" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_column="0" 
       android:text="Name" 
       android:textColor="@android:color/background_light" 
       android:textAlignment="center"/> 


      <TextView 
       android:id="@+id/textView2" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_column="1" 
       android:text="Qty" 
       android:textColor="@android:color/background_light" 
       android:textAlignment="center"/> 

      <TextView 
       android:id="@+id/textView3" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_column="1" 
       android:text="Price" 
       android:textColor="@android:color/background_light" 
       android:textAlignment="center"/> 

      <TextView 
       android:id="@+id/textView4" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_column="1" 
       android:text="Subtotal" 
       android:textColor="@android:color/background_light" 
       android:textAlignment="center"/> 


     </TableRow> 

    </TableLayout> 


    <ScrollView 
     android:layout_height="wrap_content" 
     android:layout_width="wrap_content"> 
     <LinearLayout 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:orientation="vertical"> 


      <!--/*Add your content here*/--> 


     </LinearLayout> 
    </ScrollView> 
    </GridLayout> 

    <GridLayout 
     android:layout_height="wrap_content" 
     android:layout_width="wrap_content" 
     android:layout_alignParentBottom="true" 
     android:columnCount="1" 
     android:rowCount="5" 
     > 
    <TableLayout 
     android:layout_height="wrap_content" 
     android:layout_width="match_parent" 
     android:stretchColumns="0,1,2,3" 
     android:layout_gravity="bottom" 
     > 
     <TableRow 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:background="@android:color/background_dark" 
      android:gravity="center_horizontal"> 

      <TextView 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_column="2" 
       android:text="Total" 
       android:textColor="@android:color/background_light" 
       android:textAlignment="center"/> 

      <TextView 
       android:id="@+id/total" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_column="3" 
       android:textColor="@android:color/background_light" 
       android:textAlignment="center"/> 


     </TableRow> 

     <TableRow 
      android:minHeight="40dp"> 

      <Button 
       android:id="@+id/cashOut" 
       style="@style/Widget.AppCompat.Button.Borderless" 
       android:layout_width="wrap_content" 
       android:layout_height="match_parent" 
       android:layout_span="4" 
       android:background="@android:color/holo_blue_dark" 
       android:minHeight="0dp" 
       android:minWidth="0dp" 
       android:onClick="addItem" 
       android:text="Cash Out" 
       android:textAppearance="@style/TextAppearance.AppCompat.Body1" /> 

     </TableRow> 
    </TableLayout> 

</GridLayout> 

</RelativeLayout> 
+0

尾行並沒有消失,但仍然滾動不工作... – Ahnaf

+0

你能發表你的更新代碼的要點嗎? –

+0

現在它解決了..使用tablelayout而不是線性佈局...感謝引導我走向正確的方向.. – Ahnaf

0
votes
answers
26 views
+10

XML element with attribute and content using JAXB

How can I generate the following XML using JAXB?

<sport type="" gender="">
    sport description
</sport>
0
votes
answers
34 views
+10

向上滾動viewpager時摺疊標題視圖

0

我想在滾動視圖分頁器時摺疊我的標題視圖。 在下面的圖像relativelayout3是我試圖尋找我要崩潰的佈局..向上滾動viewpager時摺疊標題視圖

example

喜歡的東西在應用頁面Play商店中的預覽圖像崩潰..

和relativelayout3以下行,但它沒有工作

app:layout_scrollFlags="scroll|enterAlways" 

這我完整的XML,

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    xmlns:app="http://schemas.android.com/apk/res-auto"> 
    <ScrollView 
     android:layout_width="match_parent" 
     android:layout_height="match_parent"> 
     <RelativeLayout 
      android:layout_width="match_parent" 
      android:layout_height="match_parent"> 
      <RelativeLayout 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:id="@+id/relativeLayout3" 
       app:layout_scrollFlags="scroll|enterAlways" 
       > 
    <RelativeLayout 
     android:layout_width="match_parent" 
     android:layout_height="55dp" 
     android:id="@+id/toolbar" 
     android:background="@color/cornflower_blue_two" 
     android:elevation="5dp"> 

     <ImageButton 
      android:id="@+id/more" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_alignParentEnd="true" 
      android:layout_centerVertical="true" 
      android:layout_marginEnd="10dp" 
      android:background="@null" 
      android:src="@drawable/ic_dots_vertical" /> 

     <ImageButton 
      android:id="@+id/back" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_alignParentStart="true" 
      android:layout_centerVertical="true" 
      android:layout_marginEnd="5dp" 
      android:layout_marginStart="10dp" 
      android:background="@null" 
      android:src="@drawable/ic_arrow_left" /> 

    </RelativeLayout> 
    <ss.com.bannerslider.views.BannerSlider 
     android:id="@+id/slider" 
     android:layout_width="match_parent" 
     android:layout_height="250dp" 
     android:background="@color/blue" 
     android:layout_below="@id/toolbar" 
     /> 
      </RelativeLayout> 

      <RelativeLayout 
       android:layout_width="match_parent" 
       android:layout_height="match_parent" 
       android:layout_alignParentStart="true" 
       android:layout_below="@+id/relativeLayout3"> 

       <TextView 
        android:id="@+id/product" 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content" 
        android:layout_margin="10dp" 
        android:text="Blah Blah" 
        android:textColor="@color/dark_gray" 
        android:textSize="25sp" 
        android:textStyle="bold" /> 

       <TextView 
        android:id="@+id/brand" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_alignStart="@+id/product" 
        android:layout_below="@+id/product" 
        android:text="Blah inc." 
        android:textSize="20sp" 
        android:textStyle="bold" /> 

       <TextView 
        android:id="@+id/ratings" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_alignBaseline="@+id/brand" 
        android:layout_alignBottom="@+id/brand" 
        android:layout_marginStart="10dp" 
        android:layout_toEndOf="@+id/brand" 
        android:background="@color/ratings" 
        android:paddingEnd="10dp" 
        android:paddingStart="10dp" 
        android:text="4.7" 
        android:textColor="@color/white" 
        android:textSize="20sp" 
        android:textStyle="bold" /> 

       <android.support.design.widget.TabLayout 
        android:id="@+id/tabLayout" 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content" 
        android:layout_alignParentStart="true" 
        android:layout_below="@+id/brand" 
        android:layout_marginTop="14dp" 
        app:tabGravity="fill" 
        app:tabMode="fixed" /> 

       <android.support.v4.view.ViewPager 
        android:id="@+id/pager" 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content" 
        android:layout_alignParentStart="true" 
        android:layout_below="@+id/tabLayout" /> 

      </RelativeLayout> 
     </RelativeLayout> 
    </ScrollView> 

</RelativeLayout> 
沙发
0
1

考慮使用CollapsingToolbarLayout。請參考Collapsing Toolbar Example.

板凳
0
1
<android.support.design.widget.CoordinatorLayout 
xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:app="http://schemas.android.com/apk/res-auto" 
android:layout_width="match_parent" 
android:layout_height="match_parent"> 

<android.support.design.widget.AppBarLayout 
    android:layout_width="match_parent" 
    android:layout_height="250dp" 
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"> 

    <android.support.design.widget.CollapsingToolbarLayout 
     android:id="@+id/collapsing_toolbar" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     app:contentScrim="?attr/colorPrimary" 
     app:layout_scrollFlags="scroll|exitUntilCollapsed"> 

     <ImageView 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:background="@drawable/cartoon" 
      android:scaleType="centerCrop" 
      app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed" 
      app:layout_collapseMode="parallax" /> 

     <android.support.v7.widget.Toolbar 
      android:id="@+id/toolbar" 
      android:layout_width="match_parent" 
      android:layout_height="?attr/actionBarSize" 
      app:layout_collapseMode="pin" /> 

    </android.support.design.widget.CollapsingToolbarLayout> 

    </android.support.design.widget.AppBarLayout> 

    <android.support.v4.widget.NestedScrollView 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:background="#ffe5e5" 
     app:layout_behavior="@string/appbar_scrolling_view_behavior"> 

     <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:orientation="vertical" 
     android:paddingTop="10dp"> 
     <include layout="@layout/card_layout" /> 
     <include layout="@layout/card_layout" /> 
     <include layout="@layout/card_layout" /> 
     </LinearLayout> 

    </android.support.v4.widget.NestedScrollView> 

</android.support.design.widget.CoordinatorLayout> 

輸出

enter image description here

Reference

+0

@NoobCoder試試我的代碼,將工作或你可以參考我貼 – vinay

+0

參考鏈接如果它有助於你不忘記upvote – vinay

171
votes
answers
24 views
+10

Using SimpleXML to create an XML object from scratch

Is it possible to use PHP's SimpleXML functions to create an XML object from scratch? Looking through the function list, there's ways to import an existing XML string into an object that you can then manipulate, but if I just want to generate an XML object programmatically from scratch, what's the best way to do that?

I figured out that you can use simplexml_load_string() and pass in the root string that you want, and then you've got an object you can manipulate by adding children... although this seems like kind of a hack, since I have to actually hardcode some XML into the string before it can be loaded.

I've done it using the DOMDocument functions, although it's a little confusing because I'm not sure what the DOM has to do with creating a pure XML document... so maybe it's just badly named :-)

up vote 134 down vote accepted favorite
沙发
+1340
+50

Sure you can. Eg.

<?php
$newsXML = new SimpleXMLElement("<news></news>");
$newsXML->addAttribute('newsPagePrefix', 'value goes here');
$newsIntro = $newsXML->addChild('content');
$newsIntro->addAttribute('type', 'latest');
Header('Content-type: text/xml');
echo $newsXML->asXML();
?>

Output

<?xml version="1.0"?>
<news newsPagePrefix="value goes here">
    <content type="latest"/>
</news>

Have fun.

在這與@Stefan和@ PhiLho的答案之間,這似乎是最簡單和直截了當的。與此同時,我想知道表現是否不同。另外兩個聞起來像快速代碼。 - Camilo Martin 2011年3月27日5:42

如何將其保存為服務器中的xml文件?使其可用於我的動作代碼? - shababhsiddique 2011年10月6日15:00

@dreamwerx也許我錯過了為什麼你的內容標籤沒有關閉? - Shackrock 12年12月19日21:41

@Shackrock:它關閉了,看看“>”之前的“/” - 米歇爾12年12月22日14:34

如何在內容標記之間添加一些文本。說 哇它的作品! - harishannam 2014年3月18日19:42

+210

In PHP5, you should use the Document Object Model class instead. Example:

$domDoc = new DOMDocument;
$rootElt = $domDoc->createElement('root');
$rootNode = $domDoc->appendChild($rootElt);

$subElt = $domDoc->createElement('foo');
$attr = $domDoc->createAttribute('ah');
$attrVal = $domDoc->createTextNode('OK');
$attr->appendChild($attrVal);
$subElt->appendChild($attr);
$subNode = $rootNode->appendChild($subElt);

$textNode = $domDoc->createTextNode('Wow, it works!');
$subNode->appendChild($textNode);

echo htmlentities($domDoc->saveXML());

DOM API非常冗長!我希望能夠做一些像$ elem-> append($ doc-> p('This is a paragraph')); 即使附加文字也是兩行雜務。我喜歡$ elem-> append('Some text')之類的東西; - thomasrutter 2016年6月29日2:09

在我看來,這很大程度上取決於你計劃做什麼。如果您想要基本和快速的功能,SimpleXML是完美的!但無論如何:問題是“使用SimpleXML從頭開始創建XML對象” - 所以偏離主題,抱歉。 - Stephan Weinhold於17年1月24日上午10:01

+160

Please see my answer here. As dreamwerx.myopenid.com points out, it is possible to do this with SimpleXML, but the DOM extension would be the better and more flexible way. Additionally there is a third way: using XMLWriter. It's much more simple to use than the DOM and therefore it's my preferred way of writing XML documents from scratch.

$w=new XMLWriter();
$w->openMemory();
$w->startDocument('1.0','UTF-8');
$w->startElement("root");
    $w->writeAttribute("ah", "OK");
    $w->text('Wow, it works!');
$w->endElement();
echo htmlentities($w->outputMemory(true));

By the way: DOM stands for Document Object Model; this is the standardized API into XML documents.

如果您打算直接輸出到XML代碼而不進行任何操作,那麼XMLwriter就很好。進一步的操作(移動元素,插入元素)實際上是不可能的。 - thomasrutter 2016年6月29日2:11

更新鏈接(我認為)php.net/manual/en/intro.xmlwriter.php,php.net/manual/en/book.dom.php - chris85 2016年8月11日15:21

0
votes
answers
40 views
+10

春天-TX:無法找到春天NamespaceHandler XML模式命名空間[http://www.springframework.org/schema/tx]

0

爲什麼我仍然得到呢?春天-TX:無法找到春天NamespaceHandler XML模式命名空間[http://www.springframework.org/schema/tx]

Exception in thread "main" org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to import bean definitions from relative location [../beans/Character.xml] 
Offending resource: class path resource [spring/config/beanLocations.xml]; nested exception is org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/tx] 
Offending resource: class path resource [spring/beans/Character.xml] 

     at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:72) 

我讀過許多文章中針對此問題,配置爲根據他們我的XML-S。

我的問題的XML看起來像這樣:

<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:tx="http://www.springframework.org/schema/tx" 
xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd 
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx.xsd"> 

    <!-- Character Data Access Object --> 
    <bean id="characterDao" class="com.got.common.dao.CharacterDao" > 
    <property name="sessionFactory" ref="sessionFactory"/> 
    </bean> 

    <tx:annotation-driven/> 
    <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> 
    <property name="sessionFactory" ref="sessionFactory"/> 
    </bean> 
</beans> 

春-TX包括在我的pom.xml:

<dependency> 
    <groupId>org.springframework</groupId> 
    <artifactId>spring-tx</artifactId> 
    <version>5.0.2.RELEASE</version> 
</dependency> 

beanLocations.xml

<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:tx="http://www.springframework.org/schema/tx" 
xmlns:aop="http://www.springframework.org/schema/aop" 
xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd 
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop.xsd 
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx.xsd"> 


     <!-- Database Configuration --> 
     <import resource="../database/DataSource.xml"/> 
     <import resource="../database/hibernate.xml"/> 

     <!-- Beans Declaration --> 
     <import resource="../beans/Character.xml"/> 

</beans> 

組裝插件

<build> 
    <plugins> 
     <plugin> 
     <groupId>org.apache.maven.plugins</groupId> 
     <artifactId>maven-assembly-plugin</artifactId> 
     <version>3.1.0</version> 
     <executions> 
      <execution> 
      <phase>package</phase> 
      <goals> 
       <goal>single</goal> 
      </goals> 
      </execution> 
     </executions> 
     <configuration> 
      <descriptorRefs> 
      <descriptorRef>jar-with-dependencies</descriptorRef> 
      </descriptorRefs> 
      <archive> 
      <manifest> 
       <addClasspath>true</addClasspath> 
       <classpathPrefix>lib/</classpathPrefix> 
       <mainClass>com.got.common.App</mainClass> 
      </manifest> 
      </archive> 
     </configuration> 
     </plugin> 
    </plugins> 
    </build> 

我不知道該AOP必須被包括在內,但它的存在。 這個命名空間有什麼問題?我想停止拉我的頭髮,所以請告訴我這個命名空間無法找到的原因。

+0

你證實春天-TX庫實際上是放在你的war文件? – eis

+0

另外,你的'spring/config/beanLocations.xml'中有什麼?某種嵌套定義? – eis

+0

不是,但maven-assembly-plugin應該放在那裏。 (這是一個jar文件。)我在一秒鐘內包含'beanLocations.xml'。 – ntj

沙发
0
1

的問題可能是由您的使用匯編插件,它不明白春天處理機制,並覆蓋在spring.handlers文件處理程序定義造成的。行爲在這個線程中討論:Idea to avoid that spring.handlers/spring.schemas get overwritten when merging multiple spring dependencies in a single jar

爲了避免這個問題,一個選項是使用陰影插件爲您的目的,如建議here

+0

我希望這個答案能解決我的問題,所以我假設你的解決方案可以被接受,謝謝。 – ntj

+1

[此](https://issues.apache.org/jira/browse/MASSEMBLY-360)爲約組裝插件行爲錯誤條目:有趣的部分是,它是權利2010已固定的,測試用例好。看起來似乎並沒有,因爲人們似乎仍然遇到這個問題,所以示例項目證明問題並在那裏發表評論可能會使它在彙編插件(修復程序所屬的地方)中得到修復。他們已經有一個過濾器來處理這個問題,但我想這只是無法正常工作。 – eis

+1

它的工作原理,經過幾個小時的苦難後,無法感謝你足夠的這個鏈接。 – ntj

0
votes
answers
69 views
+10

Sandcastle幫助文件生成器項目沒有顯示在Visual Studio 2017企業

0

我從https://github.com/EWSoftware/SHFB/releases安裝SHFBInstaller_v2017.5.15.0.zip。在完成引導安裝後,我啓動了Visual Studio,打開了一個已經存在的C#控制檯應用程序,當我去添加一個新項目到解決方案時,沒有列出Sandcastle Help File Builder項目。下面是我可以在Visual Studio中看到的選項:Sandcastle幫助文件生成器項目沒有顯示在Visual Studio 2017企業

enter image description here

我重新啓動我的電腦,看看是否會解決什麼,但事實並非如此。我不知道爲什麼我遇到這個問題。我之前使用過沙堡,沒有遇到過這種情況。任何幫助是極大的讚賞。

沙发
0
1

該項目位於文檔類別中。 Visual C#類別用於C#編碼項目,Sandcastle文檔不是。

267
votes
answers
32 views
+10

How to add image in a TextView text?

I've searched around on Google and came across this site where I found a question similar to mine in which how to include a image in a TextView text, for example "hello my name is [image]", and the answer was this:

ImageSpan is = new ImageSpan(context, resId);
text.setSpan(is, index, index + strLength, 0);

I would like to know in this code,

  1. What am I supposed to type or do in the context?
  2. Am I supposed to do something to the text.setSpan() like import or reference or leave it text?

If someone can break this down for me that would be much appreciated.

up vote 179 down vote accepted favorite
沙发
+1790
+50

Try this ..

    txtview.setCompoundDrawablesWithIntrinsicBounds(
                    R.drawable.image, 0, 0, 0);

Also see this.. http://developer.android.com/reference/android/widget/TextView.html

Try this in xml file

    <TextView
        android:id="@+id/txtStatus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:drawableLeft="@drawable/image"
        android:drawablePadding="5dp"
        android:singleLine="true"
        android:text="@string/name"/>
+680

com/xyz/customandroid/ TextViewWithImages .java:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.text.Spannable;
import android.text.style.ImageSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;

public class TextViewWithImages extends TextView {

    public TextViewWithImages(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
    public TextViewWithImages(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public TextViewWithImages(Context context) {
        super(context);
    }
    @Override
    public void setText(CharSequence text, BufferType type) {
        Spannable s = getTextWithImages(getContext(), text);
        super.setText(s, BufferType.SPANNABLE);
    }

    private static final Spannable.Factory spannableFactory = Spannable.Factory.getInstance();

    private static boolean addImages(Context context, Spannable spannable) {
        Pattern refImg = Pattern.compile("\Q[img src=\E([a-zA-Z0-9_]+?)\Q/]\E");
        boolean hasChanges = false;

        Matcher matcher = refImg.matcher(spannable);
    while (matcher.find()) {
        boolean set = true;
        for (ImageSpan span : spannable.getSpans(matcher.start(), matcher.end(), ImageSpan.class)) {
            if (spannable.getSpanStart(span) >= matcher.start()
             && spannable.getSpanEnd(span) <= matcher.end()
               ) {
                spannable.removeSpan(span);
            } else {
                set = false;
                break;
            }
        }
        String resname = spannable.subSequence(matcher.start(1), matcher.end(1)).toString().trim();
        int id = context.getResources().getIdentifier(resname, "drawable", context.getPackageName());
        if (set) {
            hasChanges = true;
            spannable.setSpan(  new ImageSpan(context, id),
                                matcher.start(),
                                matcher.end(),
                                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                             );
        }
    }

        return hasChanges;
    }
    private static Spannable getTextWithImages(Context context, CharSequence text) {
        Spannable spannable = spannableFactory.newSpannable(text);
        addImages(context, spannable);
        return spannable;
    }
}

Use:

in res/layout/mylayout.xml:

            <com.xyz.customandroid.TextViewWithImages
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#FFFFFF00"
                android:text="@string/can_try_again"
                android:textSize="12dip"
                style=...
                />

Note that if you place TextViewWithImages.java in some location other than com/xyz/customandroid/, you also must change the package name, com.xyz.customandroid above.

in res/values/strings.xml:

<string name="can_try_again">Press [img src=ok16/] to accept or [img src=retry16/] to retry</string>

where ok16.png and retry16.png are icons in the res/drawable/ folder

@AnasAzeem你能通過ImageView顯示ok16和retry16“正常”嗎?您是否指定TextViewWithImages代替TextView? - 18446744073709551615 2014年6月4日5:40

真棒!謝謝! - Solata 2014年7月3日12:06

它的工作,但我不能設置圖像的高度寬度,也沒有得到圖像的文本中心 - Rajesh Kosht​​i 2016年7月18日在9:53

它是一個很棒的類,直到你在發布版本中打包它。它崩潰了,我仍然無法找到原因。甚至在proguard的-keep中標記了這個類。仍然沒有運氣。或者也許我使用的圖像是矢量,這就是為什麼它可能會崩潰。我不知道。 - Uday 17年6月6日3:14

+100

This answer is based on this excellent answer by 18446744073709551615. Their solution, though helpful, does not size the image icon with the surrounding text. It also doesn't set the icon colour to that of the surrounding text.

The solution below takes a white, square icon and makes it fit the size and colour of the surrounding text.

public class TextViewWithImages extends TextView {

    private static final String DRAWABLE = "drawable";
    /**
     * Regex pattern that looks for embedded images of the format: [img src=imageName/]
     */
    public static final String PATTERN = "\Q[img src=\E([a-zA-Z0-9_]+?)\Q/]\E";

    public TextViewWithImages(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

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

    public TextViewWithImages(Context context) {
        super(context);
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        final Spannable spannable = getTextWithImages(getContext(), text, getLineHeight(), getCurrentTextColor());
        super.setText(spannable, BufferType.SPANNABLE);
    }

    private static Spannable getTextWithImages(Context context, CharSequence text, int lineHeight, int colour) {
        final Spannable spannable = Spannable.Factory.getInstance().newSpannable(text);
        addImages(context, spannable, lineHeight, colour);
        return spannable;
    }

    private static boolean addImages(Context context, Spannable spannable, int lineHeight, int colour) {
        final Pattern refImg = Pattern.compile(PATTERN);
        boolean hasChanges = false;

        final Matcher matcher = refImg.matcher(spannable);
        while (matcher.find()) {
            boolean set = true;
            for (ImageSpan span : spannable.getSpans(matcher.start(), matcher.end(), ImageSpan.class)) {
                if (spannable.getSpanStart(span) >= matcher.start()
                        && spannable.getSpanEnd(span) <= matcher.end()) {
                    spannable.removeSpan(span);
                } else {
                    set = false;
                    break;
                }
            }
            final String resName = spannable.subSequence(matcher.start(1), matcher.end(1)).toString().trim();
            final int id = context.getResources().getIdentifier(resName, DRAWABLE, context.getPackageName());
            if (set) {
                hasChanges = true;
                spannable.setSpan(makeImageSpan(context, id, lineHeight, colour),
                        matcher.start(),
                        matcher.end(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                );
            }
        }
        return hasChanges;
    }

    /**
     * Create an ImageSpan for the given icon drawable. This also sets the image size and colour.
     * Works best with a white, square icon because of the colouring and resizing.
     *
     * @param context       The Android Context.
     * @param drawableResId A drawable resource Id.
     * @param size          The desired size (i.e. width and height) of the image icon in pixels.
     *                      Use the lineHeight of the TextView to make the image inline with the
     *                      surrounding text.
     * @param colour        The colour (careful: NOT a resource Id) to apply to the image.
     * @return An ImageSpan, aligned with the bottom of the text.
     */
    private static ImageSpan makeImageSpan(Context context, int drawableResId, int size, int colour) {
        final Drawable drawable = context.getResources().getDrawable(drawableResId);
        drawable.mutate();
        drawable.setColorFilter(colour, PorterDuff.Mode.MULTIPLY);
        drawable.setBounds(0, 0, size, size);
        return new ImageSpan(drawable, ImageSpan.ALIGN_BOTTOM);
    }

}

How to use:

Simply embed references to the desired icons in the text. It doesn't matter whether the text is set programatically through textView.setText(R.string.string_resource); or if it's set in xml.

To embed a drawable icon named example.png, include the following string in the text: [img src=example/].

For example, a string resource might look like this:

<string name="string_resource">This [img src=example/] is an icon.</string>

這是一個很好的解決方案。我建議只做一個改進:在drawable.setColorFilter之前添加drawable.mutate(); 如果不這樣做,您將在應用程序的其他部分使用不同顏色的drawable。 - moondroid 2017年3月27日8:26

@moondroid感謝您的建議,我相應地編輯了答案。 - 一名博世曼於2017年3月27日12:11

實際上我有一個問題,因為我的drawable不是正方形,這個解決方案將總是使drawable寬度與drawable高度相同,它將不成比例地調整我的drawable - HendraWD於8月31日在10:47

+100

I tried many different solutions and this for me was the best:

SpannableStringBuilder ssb = new SpannableStringBuilder(" Hello world!");
ssb.setSpan(new ImageSpan(context, R.drawable.image), 0, 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
tv_text.setText(ssb, TextView.BufferType.SPANNABLE);

This code uses a minimum of memory.

在那種情況下圖像添加但與文本基線對齊我想與文本頂部對齊你能幫助我 - humayoon siddique 2010年8月10日在6:45

它有效,但我們如何根據文字大小調整圖像圖標 - sunil kushwah 2017年9月7日11:03

0

This is partly based on this earlier answer above by @A Boschman. In that solution, I found that the input size of the image greatly affected the ability of makeImageSpan() to properly center-align the image. Additionally, I found that the solution affected text spacing by creating unnecessary line spacing.

I found BaseImageSpan (from Facebook's Fresco library) to do the job particularly well:

 /**
 * Create an ImageSpan for the given icon drawable. This also sets the image size. Works best
 * with a square icon because of the sizing
 *
 * @param context       The Android Context.
 * @param drawableResId A drawable resource Id.
 * @param size          The desired size (i.e. width and height) of the image icon in pixels.
 *                      Use the lineHeight of the TextView to make the image inline with the
 *                      surrounding text.
 * @return An ImageSpan, aligned with the bottom of the text.
 */
private static BetterImageSpan makeImageSpan(Context context, int drawableResId, int size) {
    final Drawable drawable = context.getResources().getDrawable(drawableResId);
    drawable.mutate();
    drawable.setBounds(0, 0, size, size);
    return new BetterImageSpan(drawable, BetterImageSpan.ALIGN_CENTER);
}

Then supply your betterImageSpan instance to spannable.setSpan() as usual

0
votes
answers
40 views
+10

兩個不同的佈局不工作在單個活動

1

我有兩個xml佈局與一個活動我用setContentView()調用它們,但是當我調用它調用的第二個視圖,但不工作。 這裏是代碼: 當我點擊第二個佈局顯示的按鈕,但其上的按鈕不起作用。請幫助兩個不同的佈局不工作在單個活動

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    //setContentView(R.layout.activity_reset_pas); 
    setContentView(R.layout.forpasrest); 

    fok.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 
       fok.setBackgroundColor(Color.rgb(220, 215, 255)); 
       setContentView(R.layout.activity_reset_pas); 

       flag=false; 
      } 

    }); 

    fback.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 
       fback.setBackgroundColor(Color.rgb(220, 215, 255)); 

       Intent intent = new Intent(ResetPasActivity.this,SignInActivity.class); 
       startActivity(intent); 
       finish(); 

      } 
    }); 

    if(flag==false){ 

     ok.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 

        Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show(); 

      } 
     }); 

     back.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 
       back.setBackgroundColor(Color.rgb(220, 215, 255)); 
       Intent intent = new Intent(ResetPasActivity.this,SignInActivity.class); 
       startActivity(intent); 
       finish(); 
      } 
     }); 
    } 
} 
+0

這可能有助於[http://stackoverflow.com/questions/7017428/switching-between-2-layouts-in-android-activity](http://stackoverflow.com/questions/7017428/switching-between- 2-layouts-in-android-activity) – sergiomse 2014-08-31 15:36:56

+0

佈局顯示,但是當我嘗試在第二個佈局上工作時,有點擊按鈕的問題,因爲代碼顯示 – Awais 2014-08-31 15:41:32

+0

當我調用setContentView(second_layout)時,它顯示正常,但它不工作 – Awais 2014-08-31 15:42:20

沙发
0
0

您應該爲第二個XML佈局創建第二個活動,而不是嘗試更改單個活動的佈局。有關詳細信息,請參閱Starting Another Activity

板凳
0
-1

爲了增加sergiome的評論:你應該初始化okback按鈕你在這裏setContentView(R.layout.activity_reset_pas)設置你的第二個佈局。這是修改後的代碼。

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    //setContentView(R.layout.activity_reset_pas); 
    setContentView(R.layout.forpasrest); 

    fok.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       buildSecondLayout(); 
      } 

    }); 

    fback.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 
       fback.setBackgroundColor(Color.rgb(220, 215, 255)); 

       Intent intent = new Intent(ResetPasActivity.this,SignInActivity.class); 
       startActivity(intent); 
       finish(); 

      } 
    }); 
} 

private void buildSecondLayout() { 
    fok.setBackgroundColor(Color.rgb(220, 215, 255)); 
    setContentView(R.layout.activity_reset_pas); 

    final Button ok = (Button)findViewById(R.id.yourButtonIdForOk); 
    final Button back = (Button)findViewById(R.id.yourButtonIdForBack); 

    ok.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 

      Toast.makeText(getApplicationContext(), result, 
        Toast.LENGTH_SHORT).show(); 

     } 
    }); 

    back.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      back.setBackgroundColor(Color.rgb(220, 215, 255)); 
      Intent intent = new Intent(ResetPasActivity.this, 
        SignInActivity.class); 
      startActivity(intent); 
      finish(); 
     } 
    }); 
} 

你的代碼的流程看起來相當混亂,我甚至不知道如何向你解釋問題。無論如何,請嘗試一下代碼,看看它是否適合你。

+0

首選的解決方案是使用第二個活動。 – 2014-09-01 02:57:12

+0

爲什麼downvote?我認爲兩次調用setContentView沒有任何問題。作爲參考:http://stackoverflow.com/questions/5808026/side-effects-of-calling-activity-setcontentview-twice-in-a-row 只是因爲你認爲你的解決方案更好,你的聲譽是更高不會給你降低我的權利。我的答案正在起作用,他想看到的唯一一件解決方案就是他的代碼無法正常工作。 – chjarder 2014-09-01 03:26:50

+0

「爲什麼downvote?」因爲我認爲這個答案「沒有用」,因爲它促成了糟糕的編程實踐。創建兩個單獨的活動更清潔,更容易維護。 – 2014-09-01 03:35:09